package cbbx_sm.livecamera;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

@SuppressWarnings("serial")
public class CameraObject extends Thread implements Serializable{

	private URL CamURL;
	public BufferedImage lastImgRead;
	public long timestampOfLastImgRead;
	protected int id;
	private File imageDir = null;
	private Long startTimeStamp = null;
	public CameraObject(int id, String URL){
		this.id=id;
		
        Authenticator.setDefault(new MyAuthenticator("rescue","rescue"));
        if (URL!=null)
			try {
				CamURL = new URL(URL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}		
	}
	public void getImage(){
		try {
			this.lastImgRead = ImageIO.read(CamURL);
			this.timestampOfLastImgRead = System.currentTimeMillis();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void getImageAsynched(){
		if (lastImgRead == null){
			getImage();
			this.start();
		}
	}
	public void storeImageAsynched(File imageDir, long startTimeStamp){
		this.imageDir = imageDir;
		this.startTimeStamp  = startTimeStamp;
		if (!this.isAlive())
			getImageAsynched();
	}
	
	public void run(){
		while(true){
			getImage();
			if (imageDir!=null)
				try {
					ImageIO.write(lastImgRead, "JPEG", new File(imageDir.getAbsoluteFile()+File.separator+getCamId()+"_"+((timestampOfLastImgRead-startTimeStamp)/1000)+".jpg"));
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}
	
	public int getCamId(){
		return id;
	}
	

}
